import { createRouter, createWebHistory } from 'vue-router'
import appMenus from '@/constants/appMenus.js'
import BasicLayout from '@/layout/BasicLayout.vue'
import ParentView from '@/layout/ParentView.vue'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../views/**/*.vue')
console.log(modules)

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    meta: {
      title: '重定向-首页',
      hidden: true
    },
    component: () => import('@/views/Home/index.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

function treeToRoute(routes, routeData) {
  console.log('routeData', routeData)
  routeData.forEach(item => {
    const route = {
      path: item.path,
      redirect: item.redirect,
      meta: {
        menuType: item.menuType,
        title: item.title,
        icon: item.icon
      }
    }
    if (item.comPath === 'BasicLayout') {
      route.component = BasicLayout
    } else if (item.comPath === 'ParentView' || item.comPath === 'RouterView') {
      route.component = ParentView
    } else {
      route.path = item.comPath
      route.component = modules[`../views${item.comPath}.vue`]
      console.log(route.path)
      console.log(route.component)
    }
    if (item.children && item.children.length > 0) {
      const children = []
      treeToRoute(children, item.children)
      route.children = children
    }
    routes.push(route)
  })
}

const routeRecordRaw = []
treeToRoute(routeRecordRaw, appMenus)
router.addRoute(routeRecordRaw[0])
export default router
